package model.doe;

public class Rectangle extends AbstractDoe {

	private double k;
	private double au;
	private double cos;
	private double av;
	private double f;
	private double r;
	private double su;
	private double sigma;
	private double sv;
	private double maxY;
	private double maxX;
	private int lno;
	private double s;


	public Rectangle(double r, double sigma, double f, double a, double wl, double maxX, double maxY, double s,
			boolean lno) {
		this.r = r;
		this.sigma = this.su = this.sv = sigma;
		this.f = f;
		this.cos = Math.cos(Math.PI * a / 180);
		this.av = r;
		this.au = r / cos;
		this.k = 2 * Math.PI / wl * 1000;
		this.maxX = maxX;
		this.maxY = maxY;
		this.lno = lno ? 1 : 0;
		this.s = s;
		
		widthPointsNumber = (int) (2*r / s);
		heightPointsNumber = (int) (2*r / s);
		
		double min1=RectangleFun1(0),max1=RectangleFun1(0);

		   double min2=RectangleFun2(0),max2=RectangleFun2(0);

		   double t,p;

		   for(t=0; t<=au; t+=s) {

		      p=RectangleFun1(t);

		      if(max1<p)  max1=p;

		      if(min1>p)  min1=p;

		   }

		   for(t=0; t<=av; t+=s) {

		      p=RectangleFun2(t);

		      if(max2<p)  max2=p;

		      if(min2>p)  min2=p;
		   }

		super.maximumValue =  max1+max2;
		super.minValue = min1+min2;
		
		
		
	}



	double RectangleFun2Add(double t,

	double _s, double a, double max) {

		double s = _s / 2;

		double c2 = s * Math.sqrt(2);

		double x = max * erf(t / c2) / erf(a / c2);

		double q = Math.abs(1 - Math.exp(-t * t / 2 / s / s));

		double p = k * (-t * t * lno / 2 + t * x -

		max * s * q * Math.sqrt(2 / Math.PI)

		/ erf(a / c2)

		) / f;

		return p;

	}

	double RectangleFun(double p1, double p2) {
		return p1 + p2;
	}

	double RectangleFun1(double u)

	{
		return RectangleFun2Add(u * cos, su, au * cos, maxX / 2);
	}

	double RectangleFun2(double v)

	{
		return RectangleFun2Add(v, sv, av, maxY / 2);
	}

	static double p = 0.3275911,

	a1 = 0.254829592,

	a2 = -0.284496736,

	a3 = 1.421413741,

	a4 = -1.453152027,

	a5 = 1.061405429;

	double erf(double x) {

		if (x < 0)
			return -ErfFun(-x);

		else
			return ErfFun(x);

	}

	double ErfFun(double x) {

		double t = 1 / (1 + p * x);

		return 1 - ((((a5 * t + a4) * t + a3) * t + a2) * t + a1) * t * Math.exp(-x * x);

	}

	@Override
	public double run(int i, int j) {	
		if (Math.sqrt(s * i * cos * s * i * cos + s * j * s * j) > r)
			return 0;
		return RectangleFun1(s * i) + RectangleFun2(s * j);
	}

}
